﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using qna.Business;
using qna.Services;
using qna.pages;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;

namespace qna.Controls
{
    public partial class AnswerControl : System.Web.UI.UserControl
    {
        public Answer a { get; set; }
        public string url = "";
        public string urlAlink = "";
        public bool b = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            //Get Current user ID, initiate answer service
            int uID = Convert.ToInt32(Parent.Page.User.Identity.Name);
            AnswerService asc = new AnswerService();
            QuestionService qsc = new QuestionService();

            ModalPopupExtender1.Hide();
            if (a == null)
            {
                content.InnerText = "Answer Missing :(";
            }
            else
            {
                AnswerService ans = new AnswerService();
                content.InnerHtml = ParseContent(a.Content);

                date.InnerText = a.DateTime.ToString();
                lblPostedBy.Text = ans.GetUserNameAns(a.Id);
                lblRating1.Text = asc.GetRating(a.Id).ToString();
                txtUpdAnswer.Text = a.Content;
                answerId.Value = a.Id.ToString();
                //set best.
                if (qsc.Get(a.QuestionID).AnswerId > 0)
                {
                    btnBest.ImageUrl = "../images/best.jpg";
                    btnBest.Attributes["onmouseover"] = "this.src='../images/best_grayscale.jpg'";
                    btnBest.Attributes["onmouseout"] = "this.src='../images/best.jpg'";

                }
                //set rating.
                bool userRated = asc.CheckIfUserRated(a.Id, uID);
                
                if (userRated == true)
                {
                    imgRating1.ImageUrl = "../images/rating_liked.jpg";
                    imgRating1.Attributes["onmouseover"] = "this.src='../images/images.jpg'";
                    imgRating1.Attributes["onmouseout"] = "this.src='../images/rating_liked.jpg'";
                }

				//hide some buttons
				if (a.UserId != Convert.ToInt32(Parent.Page.User.Identity.Name))
				{
					AnsEdit.Visible = false;
					AnsDlt.Visible = false;
					UpdateAnsPanel.Visible = false;
				}
            }

        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            b = false;
            AnswerService asc = new AnswerService();
            DateTime dt = DateTime.Now;
            a = asc.UpdateAns(a.Id, txtUpdAnswer.Text, dt);
            Parent.Page.Response.Redirect(Parent.Page.Request.RawUrl);

        }

        protected void AnsDlt_Click(object sender, ImageClickEventArgs e)
        {
            a.Delete();
            Parent.Page.Response.Redirect(Parent.Page.Request.RawUrl);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            b = false;
            ModalPopupExtender1.Hide();
        }

        protected void imgRating1_Click(object sender, ImageClickEventArgs e)
        {
            AnswerService asc = new AnswerService();
            int aID = a.Id;
            int uID = Convert.ToInt32(Parent.Page.User.Identity.Name);

            if (btnBest.ImageUrl.Equals("../images/images.jpg"))
            {
                imgRating1.ImageUrl = "../images/rating_liked.jpg";
                imgRating1.Attributes["onmouseout"] = "this.src='../images/images.jpg'";
                imgRating1.Attributes["onmouseover"] = "this.src='../images/rating_liked.jpg'";
                asc.SetRating(aID, uID);
                lblRating1.Text = asc.GetRating(aID).ToString();                
            }
            else
            {
                imgRating1.ImageUrl = "../images/images.jpg";
                imgRating1.Attributes["onmouseover"] = "this.src='../images/rating_liked.jpg'";
                imgRating1.Attributes["onmouseout"] = "this.src='../images/images.jpg'";
                asc.SetRating(aID, uID); 
                lblRating1.Text = asc.GetRating(aID).ToString();
            }
        }

        protected void btnBest_Click(object sender, ImageClickEventArgs e)
        {
            QuestionService qsc = new QuestionService();
            int uID = Convert.ToInt32(Parent.Page.User.Identity.Name);
            int qID = Convert.ToInt32(Request.QueryString["view"]);
            qsc.SelectAnswer(a.Id, qID, uID);

            if (btnBest.ImageUrl.Equals("../images/best_grayscale.jpg"))
            {
                btnBest.ImageUrl = "../images/best.jpg";
                btnBest.Attributes["onmouseover"] = "this.src='../images/best_grayscale.jpg'";
                btnBest.Attributes["onmouseout"] = "this.src='../images/best.jpg'";

            }
            else
            {
                btnBest.ImageUrl = "../images/best_grayscale.jpg";
                btnBest.Attributes["onmouseover"] = "this.src='../images/best.jpg'";
                btnBest.Attributes["onmouseout"] = "this.src='../images/best_grayscale.jpg'";

            }
        }

        private string ParseContent(string html)
        {
            if (!html.Contains("http://") && !html.Contains("https://"))
            {
                return html;
            }

            string result = "";
            using (StringReader reader = new StringReader(html))
            {
                string line, newLine, newWord = "";
                while ((line = reader.ReadLine()) != null)
                {
                    newLine = "";
                    string[] words = line.Split(new char[1] { ' ' });
                    foreach (var word in words)
                    {
                        if (RgURL.IsMatch(word))
                        {
                            //youtube
                            if (word.StartsWith("http://youtu.be/"))
                            {
                                string id = Regex.Match(word, "http://youtu.be/([^\\s]+)").Groups[1].Value;
                                newWord = "<object width=\"390\" height=\"640\">"
                                    + "<param name=\"movie\" value=\"http://www.youtube.com/v/" + id + "?version=3&amp;hl=en_GB\"></param>"
                                    + "<param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param>"
                                    + "<embed src=\"http://www.youtube.com/v/" + id + "?version=3&amp;hl=en_GB\" type=\"application/x-shockwave-flash\" width=\"640\" height=\"390\" allowscriptaccess=\"always\" allowfullscreen=\"true\" wmode=\"opaque\"></embed>"
                                    + "</object>";
                            }
                            else if (Regex.IsMatch(word, ".(png|jpg|gif)"))
                                //images
                                newWord = "<img src=\"" + word + "\" />";
                            else
                                //rest of the links
                                newWord = "<a href=\"" + word + "\" target='_blank'>" + word + "</a>";
                        }
                        else
                            newWord = word;
                        newLine += newWord + " ";
                    }
                    result += "<p>" + (newLine == " " ? "&nbsp;" : newLine) + "</p>";
                }
            }
            return result;
        }

        public Regex RgExp = new Regex(@"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase);

        public Regex RgURL = new Regex(@"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])", RegexOptions.IgnoreCase);

        protected void AnsEdit_Click(object sender, ImageClickEventArgs e)
        {
            b = true;

        }

    }
}